package cn.wind.xboot.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.lang3.ClassUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author xukk
 * @date 2018/5/4
 */
@Slf4j
public class BeanUtil extends org.apache.commons.beanutils.BeanUtils {
    public static  void copyPropertiesNoNull(final Object dest, final Object orig)
            throws IllegalAccessException, InvocationTargetException {

        // Validate existence of the specified beans
        if (dest == null) {
            throw new IllegalArgumentException
                    ("No destination bean specified");
        }
        if (orig == null) {
            throw new IllegalArgumentException("No origin bean specified");
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanUtil.copyProperties(" + dest + ", " +
                    orig + ")");
        }

        // Copy the properties, converting as necessary
        if (orig instanceof DynaBean) {
            final DynaProperty[] origDescriptors =
                    ((DynaBean) orig).getDynaClass().getDynaProperties();
            for (DynaProperty origDescriptor : origDescriptors) {
                final String name = origDescriptor.getName();
                // Need to check isReadable() for WrapDynaBean
                // (see Jira issue# BEANUTILS-61)
                if (BeanUtilsBean.getInstance().getPropertyUtils().isReadable(orig, name) &&
                        BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(dest, name)) {
                    final Object value = ((DynaBean) orig).get(name);
                    if(value!=null)
                    copyProperty(dest, name, value);
                }
            }
        } else if (orig instanceof Map) {
            @SuppressWarnings("unchecked")
            final
            // Map properties are always of type <String, Object>
                    Map<String, Object> propMap = (Map<String, Object>) orig;
            for (final Map.Entry<String, Object> entry : propMap.entrySet()) {
                final String name = entry.getKey();
                if (BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(dest, name)) {
                    if(entry.getValue()!=null)
                    copyProperty(dest, name, entry.getValue());
                }
            }
        } else /* if (orig is a standard JavaBean) */ {
            final PropertyDescriptor[] origDescriptors =
                    BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(orig);
            for (PropertyDescriptor origDescriptor : origDescriptors) {
                final String name = origDescriptor.getName();
                if ("class".equals(name)) {
                    continue; // No point in trying to set an object's class
                }
                if (BeanUtilsBean.getInstance().getPropertyUtils().isReadable(orig, name) &&
                        BeanUtilsBean.getInstance().getPropertyUtils().isWriteable(dest, name)) {
                    try {
                        final Object value =
                                BeanUtilsBean.getInstance().getPropertyUtils().getSimpleProperty(orig, name);
                        if(value!=null){
                            copyProperty(dest, name, value);
                        }
                    } catch (final NoSuchMethodException e) {
                        // Should not happen
                    }
                }
            }
        }

    }

    /** 类的属性和读方法的映射关系缓存 */
    private static final Map<Class<?>, Map<String, Method>> readMethodMappingCache = new HashMap<Class<?>, Map<String, Method>>();
    /** 类的属性和写方法的映射关系缓存 */
    private static final Map<Class<?>, Map<String, Method>> writeMethodMappingCache = new HashMap<Class<?>, Map<String, Method>>();

    /**
     * 获得类的属性和读方法的映射关系
     *
     */
    public static Map<String, Method> getReadMethodMapping(Class<?> clazz) {
        Map<String, Method> getLowerMapping = readMethodMappingCache.get(clazz);
        if(getLowerMapping != null) {
            return getLowerMapping;
        }
        getLowerMapping = new HashMap<String, Method>();
        Map<String, Method> getUpperMapping = new HashMap<String, Method>();
        Map<String, Method> isLowerMapping = new HashMap<String, Method>();
        Map<String, Method> isUpperMapping = new HashMap<String, Method>();
        for (Method method : clazz.getMethods()) {
            if(Modifier.isStatic(method.getModifiers()) || method.getParameterTypes().length > 0) {
                continue;
            }
            String methodName = method.getName();
            if(method.getReturnType() == boolean.class && methodName.startsWith("is")) {
                if(methodName.matches("^is[a-z_].*$")) {
                    isLowerMapping.put(methodName.substring(2), method);
                } else if(methodName.matches("^is[A-Z].*$")) {
                    isUpperMapping.put(methodName.substring(2, 3).toLowerCase() + methodName.substring(3), method);
                }
            } else {
                if(methodName.matches("^get[a-z_].*$")) {
                    getLowerMapping.put(methodName.substring(3), method);
                } else if(methodName.matches("^get[A-Z].*$")) {
                    getUpperMapping.put(methodName.substring(3, 4).toLowerCase() + methodName.substring(4), method);
                }
            }
        }
        for (String field : getUpperMapping.keySet()) {
            getLowerMapping.put(field, getUpperMapping.get(field));
        }
        for (String field : isLowerMapping.keySet()) {
            getLowerMapping.put(field, isLowerMapping.get(field));
        }
        for (String field : isUpperMapping.keySet()) {
            getLowerMapping.put(field, isUpperMapping.get(field));
        }
        readMethodMappingCache.put(clazz, getLowerMapping);
        return getLowerMapping;
    }

    /**
     * 获得类的属性和写方法的映射关系
     *
     */
    public static Map<String, Method> getWriteMethodMapping(Class<?> clazz) {
        Map<String, Method> setLowerMapping = writeMethodMappingCache.get(clazz);
        if(setLowerMapping != null) {
            return setLowerMapping;
        }
        setLowerMapping = new HashMap<String, Method>();
        Map<String, Method> setUpperMapping = new HashMap<String, Method>();
        for (Method method : clazz.getMethods()) {
            if(Modifier.isStatic(method.getModifiers()) || method.getParameterTypes().length != 1) {
                continue;
            }
            String methodName = method.getName();
            if(methodName.matches("^set[a-z_].*$")) {
                setLowerMapping.put(methodName.substring(3), method);
            } else if(methodName.matches("^set[A-Z].*$")) {
                setUpperMapping.put(methodName.substring(3, 4).toLowerCase() + methodName.substring(4), method);
            }
        }
        for (String field : setUpperMapping.keySet()) {
            setLowerMapping.put(field, setUpperMapping.get(field));
        }
        writeMethodMappingCache.put(clazz, setLowerMapping);
        return setLowerMapping;
    }

    /**
     * 将Map转换成beanClass指定的类型对象
     *
     */
    public static <T> T toBean(Map<String, Object> map, Class<T> beanClass) {
        try {
            T bean = beanClass.newInstance();
            Map<String, Method> writeMethodMapping = getWriteMethodMapping(beanClass);
            for (String field : map.keySet()) {
                if(!writeMethodMapping.keySet().contains(field)) {
                    continue;
                }
                Method method = writeMethodMapping.get(field);
                Object value = map.get(field);
                Object newVaule = null;
                Class<?> type = method.getParameterTypes()[0];
                if(value == null) {
                    newVaule = ObjectUtil.getInitialValue(type);
                } else if(ClassUtils.primitiveToWrapper(type).isInstance(value)) {
                    newVaule = value;
                } else {
                    newVaule = ConvertUtils.convert(value, type);
                }
                method.invoke(bean, newVaule);
            }
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将bean对象转换成Map
     */
    public static Map<String, Object> toMap(Object bean) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Method> readMethodMapping = getReadMethodMapping(bean.getClass());
        for (String field : readMethodMapping.keySet()) {
            try {
                map.put(field, readMethodMapping.get(field).invoke(bean));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return map;
    }

    /**
     * 将bean对象按fields指定的属性顺序转换成List
     *
     */
    public static List<Object> toList(Object bean, String... fields) {
        List<Object> list = new ArrayList<Object>();
        for (String field : fields) {
            try {
                list.add(new PropertyDescriptor(field, bean.getClass()).getReadMethod().invoke(bean));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return list;
    }
}
